package booyah.web;

import org.springframework.util.StringUtils;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.sql.Timestamp;

public class TimestampEditor extends PropertyEditorSupport {

    private DateFormat dateFormat;
    private boolean allowEmpty;

    public TimestampEditor() {
        dateFormat = new SimpleDateFormat("MM.dd.yy HH:mm");
        allowEmpty = true;
    }

    public TimestampEditor(DateFormat dateFormat, boolean allowEmpty) {
        this.dateFormat = dateFormat;
        this.allowEmpty = allowEmpty;
    }

    @Override
    public String getAsText() {
        Timestamp timestamp = (Timestamp) getValue();
        return timestamp == null ? "" : dateFormat.format(timestamp);
    }

    @Override
    public void setAsText(String s) throws IllegalArgumentException {
        if (allowEmpty && !StringUtils.hasText(s)) {
            setValue(null);
            return;
        }
        try {
            Date date = dateFormat.parse(s);
            Timestamp timestamp = new Timestamp(date.getTime());
            setValue(timestamp);
        }
        catch (ParseException e) {
            throw new IllegalArgumentException("Could not parse Date Time " + e.getMessage());
        }

    }
}
